package com.wandian.texas;

import java.sql.Timestamp;

import com.wandian.texas.db.CommonDaoManager;
import com.wandian.texas.db.DBMgr;
import com.wandian.texas.entity.UserInfoEntity;
import com.wandian.util.Log;

/**
 * @author long
 * @Create 2012-10-19 上午11:21:51
 * @QQ 108232706
 * @version 1.0
 * @description TexasIoHandler
 */
public class TexasIoHandler extends IoHandlerAdapter {
	@Override
	public void sessionCreated(SessionObject session) throws Exception {
		Log.debug(String.format("[TexasIoHandler]有玩家上线,ip %s,当前在线人数%s", session.ipAddress, GameData.ONLINECOUNT.get()));
	}

	@Override
	public void sessionClosed(SessionObject session) throws Exception {
		try {
			Log.debug(String.format("[TexasIoHandler]有玩家断线,ip %s,当前在线人数%s", session.ipAddress, GameData.ONLINECOUNT.get()));
			UserInfoEntity user = session.getUser();
			// 用户组删除
			UserMgr.I().loginOff(session);
			// 大厅组删除

			// 房间游戏组删除,跟线程抢了数据库
			RoomMgr.loginOff(session, -1, ThreadPool.getInstance().sessionMgrCommand());
			// 广播消息

			// 清除onlyLogin
			if (user.isCheckLogin()) {
				CommonDaoManager.GameRoomDao(0).execSql("delete from OnlyLogin where ServerIdx =? and GameId=? and Account=?", DBMgr.AccountDB, GameData.SERVER.ServerIndex, GameData.SERVER.GameId, user.userName);
				// 更新数据库状态
				if (!CommonDaoManager.UserInfoDao(0).exeSql("  UPDATE [Mutil_TexasPoker].[dbo].PlayerInfo SET  CurrentState=?,LastLogOutTime=? Where UserId=? ;", DBMgr.TexasPokerDB, 0, new Timestamp(System.currentTimeMillis()), user.userId)) {
					Log.error("[UserLoginCmd]玩家注销,保存状态失败!");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.error(e);
		}
	}

	@Override
	public void exceptionCaught(SessionObject session, Throwable cause) throws Exception {

	}
}
